<template>
  <span class="countdown-cell" :class="{ 'text-danger': isExpired }">
    {{ displayText }}
  </span>
</template>

<script setup>
import { computed, ref, onMounted, onUnmounted } from 'vue';

const props = defineProps({
  endTime: {
    type: [Number, String, Date],
    required: true
  }
});

const emit = defineEmits(['expired']);

const now = ref(Date.now());
const isExpired = ref(false);

// 计算剩余时间（毫秒）
const remainingTime = computed(() => {
  const end = new Date(props.endTime).getTime();
  return end - now.value;
});

// 显示文本
const displayText = computed(() => {
  if (isExpired.value) return '已过期';
  
  const totalSeconds = Math.floor(remainingTime.value / 1000);
  if (totalSeconds <= 0) return '00:00:00';
  
  const hours = Math.floor(totalSeconds / 3600);
  const minutes = Math.floor((totalSeconds % 3600) / 60);
  const seconds = totalSeconds % 60;
  
  return [
    hours.toString().padStart(2, '0'),
    minutes.toString().padStart(2, '0'),
    seconds.toString().padStart(2, '0')
  ].join(':');
});

// 更新当前时间
let timer = null;
const updateNow = () => {
  now.value = Date.now();
  if (remainingTime.value <= 0 && !isExpired.value) {
    isExpired.value = true;
    emit('expired');
  }
};

onMounted(() => {
  updateNow();
  timer = setInterval(updateNow, 1000);
});

onUnmounted(() => {
  clearInterval(timer);
});
</script>

<style scoped>
.countdown-cell {
  font-family: monospace;
}
.text-danger {
  color: #f56c6c;
  font-weight: bold;
}
</style>